package businessService

import (
	"go-ws-server/model/common"
	"go-ws-server/service"
	"go-ws-server/ws/manager"
	"log"

	"github.com/gorilla/websocket"
)

/* 处理 ping*/
func HandlePing(userId string, req common.WsCommonRequest, conn *websocket.Conn) {

	log.Println("调用：100002 指令；请求体为", req)

	// 回复 Pong 消息
	common.WsSuccess(conn, "Ping 成功！", nil)
}

/* 发送消息给指定用户 */
func HandleSendToUser(userId string, req common.WsCommonRequest, conn *websocket.Conn) {

	log.Println("调用：100001 指令；请求体为", req)

	dataMap, ok := req.Data.(map[string]interface{})
	if !ok {
		log.Println("❌ 请求参数 解析失败，必须是 map 类型")
		return
	}

	reciverId, ok := dataMap["reciverId"].(string)

	if !ok {
		log.Println("❌ reciverId 缺失或格式错误")
		return
	}

	content, _ := dataMap["content"].(string)

	log.Printf("💬 [%s] → [%s] : %s", userId, reciverId, content)

	err := manager.SendToUser(reciverId, dataMap)

	if err != nil {
		log.Println("❌ 发送失败:", err)
	} else {

		log.Println("✅ 消息发送成功！")

		// 操作成功, 返回值
		common.WsSuccess(conn, "消息发送成功！", nil)

	}
}

/* 查询用户列表信息*/
func GetUserList(userId string, req common.WsCommonRequest, conn *websocket.Conn) {

	userList, err := service.GetOnlineUsers()
	if err != nil {
		log.Println("❌ 获取在线用户列表失败:", err)
		common.WsFail(conn, "获取在线用户列表失败")
		return
	}
	log.Println("在线用户列表:", userList)

	var result []map[string]interface{}

	for _, user := range userList {
		m := map[string]interface{}{
			"ID":               user.ID,
			"UserID":           user.UserID,
			"UserName":         user.UserName,
			"Phone":            user.Phone,
			"AvatarURL":        user.AvatarURL,
			"UserIntroduction": user.UserIntroduction,
			"Status":           user.Status,
			"LastOnlineTime":   user.LastOnlineTime,
			"Used":             user.Used,
			"CreateTime":       user.CreateTime,
			"UpdateTime":       user.UpdateTime,
		}

		// 添加新字段
		m["lastMessageType"] = "text" // 或根据业务判断是否是好友
		m["unread_count"] = 0         // 假设没有未读消息
		m["lastMessage"] = "这是最后一条消息"

		result = append(result, m)
	}

	common.WsSuccessCmd(conn, 1100003, "获取在线用户列表成功！", result)

	// common.WsSuccessCmd(conn, 1100003, "获取在线用户列表成功！", userList)
}
